# 运算符的优先级配置
operator_precedences = {'+': 1, '-': 1, '*': 2, '/': 2}


def tokenize(expression):
    """ 将表达式分割成数字、运算符和括号的列表

    :param expression: 表达式
    :return: 分词列表
    """
    tokens = []
    current_num = ''
    for char in expression:
        if char.isdigit() or char == '.':
            current_num += char
        else:
            if current_num:
                tokens.append(float(current_num))
                current_num = ''
            if char.strip():
                tokens.append(char)
    if current_num:
        tokens.append(float(current_num))
    return tokens


def apply_operator(operators, values):
    """ 根据运算符进行计算

    :param operators: 运算符列表
    :param values: 数字列表
    :return:
    """
    operator = operators.pop()
    right = values.pop()
    left = values.pop()
    values.append(eval(str(left) + operator + str(right)))


def calculate(expression):
    """ 计算带括号表达式的值

    :param expression: 表达式
    :return: 结果值
    """
    tokens = tokenize(expression)
    values = []
    operators = []
    for token in tokens:
        if isinstance(token, float):
            values.append(token)
        elif token == '(':
            operators.append(token)
        elif token == ')':
            while operators and operators[-1] != '(':
                apply_operator(operators, values)
            operators.pop()
        elif token in operator_precedences:
            while operators and operators[-1] != '(' and operator_precedences.get(
                    operators[-1]) >= operator_precedences.get(token):
                apply_operator(operators, values)
            operators.append(token)
    while operators:
        apply_operator(operators, values)
    if len(values) != 1:
        raise Exception('错误：表达式无效，数字不匹配')
    return values[0]


def app():
    print("欢迎使用简易计算器小工具！")

    try:
        expression = input('请输入一个包含加减乘除和括号的表达式（例如：(2 + 3) * 4）: ')
        result = calculate(expression)
        print(f'计算结果：{result}')
    except ZeroDivisionError:
        print('错误：除数不能为0！')
    except IndexError:
        print('错误：表达式无效，运算符号不匹配！')
    except Exception as e:
        print(e)
